from PySide2.QtCore import *
from PySide2.QtWidgets import *
from PySide2.QtGui import *
import os, sys, codecs, json
from AutoSaver import AutoSaver
from Mouse_Pendant import Pendant
from Anime4K import Anime4KDialog
from pay import pay
from Widgets import OptionWidget, ImageWidget, darkStyle


def _translate(context, text, disambig):
    return QApplication.translate(context, text, disambig)


def openNewProcess():
    os.popen('%s' % sys.argv[0])


class Version(QWidget):
    """版本说明窗口"""
    def __init__(self):
        super(Version, self).__init__(parent=None)
        self.resize(350, 150)
        self.setWindowTitle('当前版本')
        layout = QGridLayout(self)
        layout.addWidget(QLabel('DD画师助手 v0.1测试版'), 0, 0, 1, 2)
        layout.addWidget(QLabel('by 神君Channel'), 1, 0, 1, 2)
        layout.addWidget(QLabel(''), 2, 0, 1, 2)
        releases_url = QLabel('')
        releases_url.setOpenExternalLinks(True)
        releases_url.setText(_translate("MainWindow", "<html><head/><body><p><a href=\"https://space.bilibili.com/637783\">\
<span style=\" text-decoration: underline; color:#cccccc;\">https://space.bilibili.com/637783</span></a></p></body></html>", None))
        layout.addWidget(releases_url, 1, 1, 1, 2, Qt.AlignRight)

        checkButton = QPushButton('检查更新')
        checkButton.setFixedHeight(40)
        checkButton.clicked.connect(self.checkUpdate)
        layout.addWidget(checkButton, 0, 2, 1, 1)

    def checkUpdate(self):
        QDesktopServices.openUrl(QUrl(r'https://gitee.com/zhimingshenjun/DD_Painter_Helper'))


class MainWindow(QMainWindow):  # 主窗口 加载了画布控件 菜单 插件 以及处理画布控件和调节页之间的通信
    def __init__(self, screenList):
        super().__init__()
        # 初始化默认设置
        self.imagePath = ''
        self.config = {
            'autoSaveConfig': [''],
            'pendantConfig': [100, 128, 15, 15, 64, True, 0, 'utils/pikaqiu.png']
        }
        if os.path.exists('utils/config.json'):
            with codecs.open('utils/config.json', 'r', 'utf8') as config:
                config = json.loads(config.read())
            self.config.update(config)  # 用本地配置覆盖默认设置
        self.config['pendantConfig'][5] = not self.config['pendantConfig'][5]
        self.clipboard = QApplication.clipboard()  # 初始化剪切板
        self.setWindowTitle('DD画师助手')
        self.setWindowFlag(Qt.WindowStaysOnTopHint)
        self.setAcceptDrops(True)  # 设置接受拖放事件
        self.resize(360, 480)
        self.imageWidget = ImageWidget(self)  # 实例化画布控件
        self.imageWidget.resizeSignal.connect(self.resizeWindow)  # 绑定信号
        self.imageWidget.openSignal.connect(self.openBrowser)
        self.imageWidget.moveSignal.connect(self.moveWindow)
        self.imageWidget.rightClickSignal.connect(self.popMenu)
        self.imageWidget.leftClickSignal.connect(self.hideMenu)
        self.imageWidget.scaleSignal.connect(self.setScaleLabel)
        self.imageWidget.mirrorSignal.connect(self.initMirrorSetting)
        self.setCentralWidget(self.imageWidget)  # 设置画布控件
        self.menuHided = False  # 隐藏菜单标志位 左键点击隐藏
        self.fileMenu = self.menuBar().addMenu('选项')  # 添加菜单
        self.fileMenu.addAction(QAction('选择图片  (可将图片拖入打开)', self, triggered=self.openBrowser))  # 绑定菜单信号
        self.fileMenu.addAction(QAction('重置图片  (空格键)', self, triggered=self.setImage))
        self.fileMenu.addAction(QAction('隐藏菜单  (单击鼠标左键)', self, triggered=self.hideMenu))
        self.fileMenu.addAction(QAction('再开一个', self, triggered=openNewProcess))
        self.optionMenu = self.menuBar().addMenu('调节')
        self.optionMenu.addAction(QAction('透明度和缩放', self, triggered=self.openOption))
        self.pluginMenu = self.menuBar().addMenu('插件')
        self.pluginMenu.addAction(QAction('保存助手', self, triggered=self.openAutoSaver))
        self.pluginMenu.addAction(QAction('鼠标挂坠', self, triggered=self.openPendant))
        self.pluginMenu.addAction(QAction('Anime4K', self, triggered=self.openAnime4K))
        self.pluginMenu.addAction(QAction('取色器', self, triggered=self.selectColor))
        self.aboutMenu = self.menuBar().addMenu('关于')
        self.version = Version()
        self.pay = pay()
        self.aboutMenu.addAction(QAction('检查更新', self, triggered=self.openVersion))
        self.aboutMenu.addAction(QAction('投喂作者', self, triggered=self.openPay))
        self.menuBarHeight = self.menuBar().height() - 4
        self.optionWidget = OptionWidget()  # 实例化调节页
        self.optionWidget.opacitySlider.currentValue.connect(self.setOpacity)  # 绑定调节页信号
        self.optionWidget.scaleSlider.currentValue.connect(self.setScale)
        self.optionWidget.rotateSlider.currentValue.connect(self.setRotate)
        self.optionWidget.mirrored.connect(self.setMirror)
        self.autoSaver = AutoSaver(self.config['autoSaveConfig'])  # 实例化自动保存助手
        self.pendant = Pendant(screenList, self.config['pendantConfig'])
        self.anime4K = Anime4KDialog()

    def openBrowser(self):  # 打开图片选择窗
        imagePath = QFileDialog.getOpenFileName(self, "请选择图片", '', "*.jpg *.jpeg *.png;;所有文件 *.*")[0]
        self.imagePath = imagePath
        if imagePath: self.imageWidget.setImagePath(imagePath)

    def dragEnterEvent(self, QDragEnterEvent):  # 拖入事件
        QDragEnterEvent.accept()

    def dropEvent(self, QDropEvent):  # 判断拖放文件
        if QDropEvent.mimeData().hasUrls:
            self.setImage(QDropEvent.mimeData().urls()[0].toLocalFile())

    def setImage(self, imagePath=''):  # 设置原始图片
        self.imagePath = imagePath
        self.imageWidget.setImagePath(imagePath, self.width(), False)

    def closeEvent(self, event):  # 关闭推出信号
        self.optionWidget.close()
        self.pendant.independent = True
        if self.pendant.option.isHidden():
            self.pendant.close()
        with codecs.open('utils/config.json', 'w', 'utf8') as config:  # 保存设置到本地
            config.write(json.dumps(self.config, ensure_ascii=False))

    def resizeWindow(self, size):  # 改变窗体大小
        self.resize(size.width(), size.height() + self.menuBar().height())

    def moveWindow(self, moveDelta):  # 移动全局坐标
        newPos = self.pos() + moveDelta
        self.move(newPos.x(), newPos.y())

    def hideMenu(self):  # 隐藏菜单栏
        if self.menuHided:
            self.fileMenu.menuAction().setVisible(True)
            self.optionMenu.menuAction().setVisible(True)
            self.pluginMenu.menuAction().setVisible(True)
            self.resize(self.width(), self.height() + self.menuBarHeight)
        else:
            self.fileMenu.menuAction().setVisible(False)
            self.optionMenu.menuAction().setVisible(False)
            self.pluginMenu.menuAction().setVisible(False)
            self.resize(self.width(), self.height() - self.menuBarHeight)
        self.menuHided = not self.menuHided

    def selectColor(self):
        QColorDialog.getColor()

    def openVersion(self):
        self.version.hide()
        self.version.show()

    def openPay(self):
        self.pay.hide()
        self.pay.show()
        self.pay.thankToBoss.start()

    def openOption(self):  # 打开调节页
        self.optionWidget.hide()
        self.optionWidget.show()

    def openAutoSaver(self):  # 打开保存助手
        if not self.autoSaver.startToken:  # 如果未处于自动保存状态
            self.autoSaver.getHwndThread.start()  # 启动获取当前进程列表的线程
        self.autoSaver.hide()
        self.autoSaver.show()

    def openPendant(self):  # 打开鼠标挂坠设置面板
        self.pendant.option.hide()
        self.pendant.option.show()
        # self.pendant.show()

    def openAnime4K(self):  # 打开Anime4K面板
        self.anime4K.videoPath = self.imagePath
        self.anime4K.hide()
        self.anime4K.show()

    def setOpacity(self, value):  # 设置透明度
        self.setWindowOpacity(value / 100)
        self.optionWidget.percentLabel.setText('%s' % value + '%')

    def setScale(self, value):  # 设置缩放
        self.imageWidget.sliderScale(value)
        scaleRate = self.imageWidget.scaleRates[value]
        self.optionWidget.scaleLabel.setText('x%s' % scaleRate)

    def setRotate(self, value):  # 设置旋转
        self.imageWidget.rotate(value)

    def setMirror(self):  # 设置镜像
        self.imageWidget.mirror()

    def setScaleLabel(self, scaleInfo):  # 同步缩放滑条的文本
        self.optionWidget.scaleSlider.setValue(scaleInfo[0])
        self.optionWidget.scaleLabel.setText('x%s' % scaleInfo[1])
        self.optionWidget.rotateSlider.setValue(0)  # 初始化option状态
        self.optionWidget.rotateLabel.setText('0 度')

    def initMirrorSetting(self):
        self.optionWidget.mirrorButton.setStyleSheet(darkStyle)
        self.optionWidget.mirrorToken = False

    def popMenu(self, point):  # 弹出右键菜单
        menu = QMenu()
        option = menu.addAction('透明度和缩放')
        openImage = menu.addAction('选择图片')
        _copy = menu.addAction('复制 (ctrl c)')
        paste = menu.addAction('粘贴 (ctrl v)')
        openNew = menu.addAction('再开一个')
        openWeb = menu.addMenu('一键打开 ►')
        pixiv = openWeb.addAction('Pixiv')
        pinterest = openWeb.addAction('Pinterest')
        banciyuan = openWeb.addAction('半次元')
        wallhaven = openWeb.addAction('wallhaven')
        colorhunt = openWeb.addAction('colorhunt')
        px500 = openWeb.addAction('500px')
        _exit = menu.addAction('退出')
        if self.menuHided:
            action = menu.exec_(self.mapToGlobal(point) + QPoint(15, 0))
        else:
            action = menu.exec_(self.mapToGlobal(point) + QPoint(15, 25))
        if action == option:
            self.optionWidget.hide()
            self.optionWidget.show()
        elif action == openImage:
            self.openBrowser()
        elif action == _copy:
            self.clipboard.setImage(self.imageWidget.image.toImage())
        elif action == paste:
            self.imageWidget.setImagePath(self.clipboard.pixmap(), self.width())
        elif action == openNew:
            openNewProcess()
        elif action == pixiv:
            QDesktopServices.openUrl(QUrl('https://www.pixiv.net/'))
        elif action == pinterest:
            QDesktopServices.openUrl(QUrl('https://www.pinterest.com/'))
        elif action == banciyuan:
            QDesktopServices.openUrl(QUrl('https://bcy.net/illust'))
        elif action == wallhaven:
            QDesktopServices.openUrl(QUrl('https://wallhaven.cc/'))
        elif action == colorhunt:
            QDesktopServices.openUrl(QUrl('https://colorhunt.co/'))
        elif action == px500:
            QDesktopServices.openUrl(QUrl('https://500px.com.cn/'))
        elif action == _exit:
            self.close()

    def keyPressEvent(self, QKeyEvent):  # 快捷键
        if QKeyEvent.key() == Qt.Key_Space:  # 空格键重置图片
            self.setImage()
        elif QKeyEvent.modifiers() == Qt.ControlModifier and QKeyEvent.key() == Qt.Key_V:  # 粘贴
            self.imageWidget.setImagePath(self.clipboard.pixmap(), self.width())
        elif QKeyEvent.modifiers() == Qt.ControlModifier and QKeyEvent.key() == Qt.Key_C:  # 复制
            self.clipboard.setImage(self.imageWidget.image.toImage())


if __name__ == '__main__':
    app = QApplication([])
    screenNumber = len(app.screens())
    desktop = QApplication.desktop()
    screenList = []
    for num in range(screenNumber):
        rect = desktop.availableGeometry(num)
        screenList.append([rect.left(), rect.top(), rect.width(), rect.height()])
    app.setStyleSheet(open('utils/qdark.qss', 'r').read())
    sysTranslator = QTranslator()
    sysTranslator.load('utils/qt_zh_CN.qm')
    app.installTranslator(sysTranslator)
    mainWindow = MainWindow(screenList)
    mainWindow.move(240, 120)
    mainWindow.show()
    app.exec_()
